package com.hsgene.order.utils;

import com.alibaba.fastjson.JSON;
import com.hsgene.common.util.exception.ErrorCode;
import com.hsgene.common.util.exception.IllegalParamException;
import com.hsgene.common.util.validation.FieldChecker;
import com.hsgene.goods.dto.specification.GoodsSpecificationDto;
import com.hsgene.order.dto.peanut.OrderCompleteProductInfo;
import com.hsgene.order.exception.OrderErrorCode;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单模块工具类
 *
 * @author wangbing
 * @version 1.0, 2018/8/7
 */
public class OrderUtils {

    /**
     * 解析下单商品序列
     *
     * @param mallGoodsIds 商城商品id列表[格式：id1,count1;id2,count2;...]
     * @return Map集合[key为商品id, value为数量]
     */
    public static Map<String, Integer> parseGoodsSequence(String mallGoodsIds) {
        FieldChecker.checkEmpty(mallGoodsIds, "mallGoodsIds");

        String[] items = mallGoodsIds.split(";");
        Map<String, Integer> result = new HashMap<>(items.length);
        for (String item : items) {
            String[] subItems = item.split(",");
            if (subItems.length != 2) {
                throw new IllegalParamException("下单商品id列表序列错误：" + mallGoodsIds);
            }
            result.put(subItems[0], Integer.valueOf(subItems[1]));
        }

        return result;
    }

    /**
     * 格式化商品规格显示
     *
     * @param specifications 商品规格列表
     * @return 商品规格字符串
     */
    public static String formatSpecification(List<GoodsSpecificationDto> specifications) {
        StringBuilder builder = new StringBuilder();
        if (!CollectionUtils.isEmpty(specifications)) {
            for (GoodsSpecificationDto dto : specifications) {
                builder.append(dto.getName())
                        .append(" * ")
                        .append(dto.getCount())
                        .append("、");
            }
        }
        String specification = builder.toString();
        return StringUtils.isBlank(specification) ? specification : specification.substring(0, specification.length()
                - 1);
    }

    /**
     * 将List<String>转成json
     * @param listStr
     * @return
     */
    public static String strListToJsonStr(List<String> listStr) {
        return JSON.toJSONString(listStr);
    }
}
